package com.my.micro.service.gateway.filter;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author Zijian Liao
 * @since 1.0.0
 */
@Component
public class MyHeaderRoutePredicateFactory extends AbstractRoutePredicateFactory<MyHeaderRoutePredicateFactory.Config> {

    /**
     * Header key.
     */
    public static final String HEADER_KEY = "header";

    /**
     * Regexp key.
     */
    public static final String REGEXP_KEY = "regexp";


    public MyHeaderRoutePredicateFactory() {
        super(MyHeaderRoutePredicateFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(HEADER_KEY, REGEXP_KEY);
    }

    @Override
    public Predicate<ServerWebExchange> apply(MyHeaderRoutePredicateFactory.Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                // 获取请求头
                List<String> values = exchange.getRequest().getHeaders()
                        .getOrDefault(config.header, Collections.emptyList());
                if (values.isEmpty()) {
                    return false;
                }
                // 判断请求头中的值是否与配置匹配
                return values.stream()
                        .anyMatch(value -> value.matches(config.regexp));
            }

            @Override
            public String toString() {
                return String.format("Header: %s=%s ", config.header, config.regexp);
            }
        };
    }

    public static class Config {
        private String header;
        private String regexp;

        public String getHeader() {
            return header;
        }

        public void setHeader(String header) {
            this.header = header;
        }

        public String getRegexp() {
            return regexp;
        }

        public void setRegexp(String regexp) {
            this.regexp = regexp;
        }
    }
}
